﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Globalization.DateTimeFormatting;
using Windows.UI.Xaml.Data;

namespace Enough.Converter
{
    /// <summary>
    /// Locale specific value converter for converting DateTime to date and time values such as 'today 13:23' or '01/24/2014 3:50 AM'
    /// </summary>
    public class DateTimeConverter : IValueConverter
    {
        private static DateTimeFormatter dateformatter = new DateTimeFormatter(YearFormat.Abbreviated, MonthFormat.Abbreviated, DayFormat.Default, DayOfWeekFormat.None);
        private static DateTimeFormatter timeFormatter = new DateTimeFormatter(HourFormat.Default, MinuteFormat.Default, SecondFormat.None);
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            if (value == null)
            {
                return null;
            }
            DateTime dt;
            if (value is DateTimeOffset)
            {
                dt = ((DateTimeOffset)value).LocalDateTime;
            }
            else if (value is DateTime)
            {
                dt = (DateTime)value;
            }
            else
            {
                return value;
            }
            string datePart = null;
            int currentYear = DateTime.Today.Year;
            if (dt.Year == currentYear)
            {
                int currentDay = DateTime.Today.DayOfYear;
                string key = null;
                if (dt.DayOfYear == currentDay)
                {
                    key = "Today";
                }
                else if (dt.DayOfYear == currentDay - 1)
                {
                    key = "Yesterday";
                }
                else if (dt.DayOfYear == currentDay + 1)
                {
                    key = "Tomorrow";
                }
                if (key != null)
                {
                    var resourceLoader = new Windows.ApplicationModel.Resources.ResourceLoader();
                    datePart = resourceLoader.GetString(key);
                    if (datePart == null)
                    {
                        datePart = key;
                    }
                }
            }
            if (datePart == null)
            {
                datePart = dateformatter.Format(dt);
            }
            string timePart = timeFormatter.Format(dt);
            return datePart + " " + timePart;
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            throw new NotImplementedException();
        }
    }
}
